package com.test.restruant.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.test.restruant.dao.DishTableDao;
import com.test.restruant.pojo.DishTable;
import com.test.restruant.service.DishTableService;
import com.test.restruant.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

//dubbo的service
@Service(timeout = 30000)
public class DishTableServiceImpl implements DishTableService {

    @Resource
    private DishTableDao dishTableDao;

    public int insert(DishTable pojo) {
        return dishTableDao.insert(pojo);
    }

    public int insertSelective(DishTable pojo) {
        return dishTableDao.insertSelective(pojo);
    }

    public int insertList(List<DishTable> pojos) {
        return dishTableDao.insertList(pojos);
    }

    public int update(DishTable pojo) {
        return dishTableDao.update(pojo);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final String REDIS_TABLE_KEY = "TABLE_LIST";

    public List<DishTable> getTableList(String name) {
        if (StringUtils.isEmpty(name)) {//全查的时候用缓存，
            //先去缓存查，如果缓存中没有，就查数据库，把查出来的结果再放缓存中
            String tableList = redisTemplate.opsForValue().get(REDIS_TABLE_KEY);
            if (tableList == null) {//缓存里没有，可能是第一次查询，也可能是key过期了
                List<DishTable> tables = dishTableDao.getTableList(name);
                redisTemplate.opsForValue().set(REDIS_TABLE_KEY, JsonUtil.getJSON(tables));
                redisTemplate.expire(REDIS_TABLE_KEY, 60, TimeUnit.MINUTES);
                return tables;
            } else {//缓存里有
                try {
                    List<DishTable> tables = JsonUtil.getObj(tableList, new TypeReference<List<DishTable>>() {
                    });
                    return tables;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dishTableDao.getTableList(name);
    }

}
